package com.gonsin.gview.common.auth.session;

import com.gonsin.gview.common.auth.AuthCommon;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtSessionRequestFilter implements Filter {

    private String jwtSecret;

    public JwtSessionRequestFilter(String jwtSecret) {
        this.jwtSecret = jwtSecret;
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String token = request.getHeader(AuthCommon.TOKEN);
        if(StringUtils.isNotEmpty(token)){
            HttpServletRequest wrapper = new JwtSessionWrapper(request, token, jwtSecret);
            HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;
            filterChain.doFilter(wrapper, httpServletResponse);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * init 和 destroy 是管理 Filter的生命周期的,与逻辑无关,所以无需实现
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}

}
